//
//  LLT_LoginViewController_LXM.m
//
//
//  Created by 刘晓萌 on 15/12/6.
//  Copyright © 2015年 刘晓萌. All rights reserved.
//

#import "LLT_LoginViewController_LXM.h"
#import "LLT_RegistViewController_LXM.h"
#import <AVOSCloud/AVOSCloud.h>

#import "LLT_TabBarController_LXM.h"
#import "LLT_MenuTableViewController_LXH.h"
#import "REFrostedViewController.h"
#import "UIViewController+LLT_LoginAndRegist_LXM.h"
#import "LLT_LoginUserListCell_LXM.h"
#import "LLT_PlayerModel.h"

#import "LLT_PlayerInfoViewController_LXM.h"
#import "LLT_AddPlayerInfoViewController_LXM.h"
#import "LLT_DataViewController_LXM.h"
#import "LLT_NewsViewController_LXH.h"
#import "LLT_VideoViewController_LXH.h"
#import "LLT_LoginViewController_LXM.h"
#import "LLT_PlayerModel.h"
@interface LLT_LoginViewController_LXM ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

//背景的滑动scrollView
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
//俩个隐藏的head
@property (weak, nonatomic) IBOutlet UIView *hiddenHead1;
//用户名
@property (weak, nonatomic) IBOutlet UITextField *userNameField;
//密码
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
//主体view
@property (weak, nonatomic) IBOutlet UIView *bodyView;
//重复滚动标记
@property (assign, nonatomic) BOOL flag;
//用户列表
@property (strong, nonatomic) NSMutableArray *usersList;
//用户(预备给跳转页面使用)
@property (strong,nonatomic) AVUser *avuser;
@property (weak, nonatomic) IBOutlet UIView *usernameAndPasswordView;
@property (strong,nonatomic) UITableView *tableView;

@property (strong,nonatomic)LLT_PlayerModel *player;
@end

@implementation LLT_LoginViewController_LXM

-(void)viewWillAppear:(BOOL)animated{
    [self makeAutoLogin];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeView];
    [self makeDelegate];
}

#pragma mark --- 懒加载
-(NSArray *)usersList{
    if (!_usersList) {
        if ([[NSUserDefaults standardUserDefaults] arrayForKey:@"usersList"]) {
            _usersList = [[NSUserDefaults standardUserDefaults] arrayForKey:@"usersList"].mutableCopy;
        }else{
            _usersList = [NSMutableArray array];
        }
    }
    return _usersList;
}

/**
 * 统一处理代理
 */
-(void)makeDelegate{
    self.userNameField.delegate = self;
    self.passwordField.delegate = self;
//    //注册cell
//    [self.userListTable registerNib:[UINib nibWithNibName:@"LLT_LoginUserListCell_LXM" bundle:nil]forCellReuseIdentifier:@"userListCell"];
    
}

/**
 * 设置页面布局
 */
-(void)makeView{
    //设置背景图滚动
    [NSTimer scheduledTimerWithTimeInterval:0.022 target:self selector:@selector(changBackImageAction) userInfo:nil repeats:YES];
    ;
   
}

/**
 * 设置滚动背景图
 */
-(void)changBackImageAction{
    NSInteger x = self.scrollView.contentOffset.x;
    NSInteger y = self.scrollView.contentOffset.y;
    if (self.flag) {
        self.scrollView.contentOffset = CGPointMake(x - 1, y);
        if ( x<= 2 ){
            self.flag = NO;
        }
    }else{
        self.scrollView.contentOffset = CGPointMake(x + 1, y);
        if (x + 2 >= (self.scrollView.contentSize.width - self.view.frame.size.width)) {
            self.flag = YES;
        }
    }
}
#pragma mark --- 设置自动登录
-(void)makeAutoLogin{
    NSUserDefaults *loginDefault = [NSUserDefaults standardUserDefaults];
    BOOL onlineFlag = [loginDefault boolForKey:@"online"];
    NSDictionary *userDic = [loginDefault dictionaryForKey:@"onlineUser"];
    if (onlineFlag) {
        [AVUser logInWithMobilePhoneNumberInBackground:userDic[@"username"] password:userDic[@"password"] block:^(AVUser *user, NSError *error) {
            if (!error) {
                [self makeMainView];
            }
        }];
    }else{
        self.avuser = [AVUser user];
    }
}
#pragma mark --- tableView的相关方法
//一个分组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
//一个组内多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.usersList.count;
}
//每行高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}
//返回cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LLT_LoginUserListCell_LXM *cell = [tableView dequeueReusableCellWithIdentifier:@"userListCell" forIndexPath:indexPath];
    NSDictionary *dic = self.usersList[indexPath.row];
    cell.label.text = [dic allKeys][0];
    cell.removeButton.userInteractionEnabled = YES;
    __weak typeof(self) weakSelf = self;
    cell.reloadTable = ^(){
        weakSelf.usersList = nil;
        [weakSelf.tableView removeFromSuperview];
        weakSelf.tableView = nil;
        [weakSelf makeTableView];
    };
    return cell;
}
//点击cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = self.usersList[indexPath.row];
    self.userNameField.text = [dic allKeys][0];
    self.tableView.hidden = YES;
}
/**
 *设置分割线顶格
 */
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
#pragma mark --- textFielf代理方法
/**
 * 文本框改变中
 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (self.tableView) {
        self.tableView.hidden = YES;
    }
    return YES;
}
/**
 * 文本框开始改变
 */
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (self.tableView) {
        self.tableView.hidden = YES;
    }
    textField.text = nil;
    //密码框
    if(textField.tag == 901){
        textField.secureTextEntry = YES;
    }
    self.bodyView.bounds = CGRectMake(0, 40, self.bodyView.frame.size.width, self.bodyView.frame.size.height);
}

/**
 * 文本框将要结束修改
 */
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    if (self.tableView) {
        self.tableView.hidden = YES;
    }
    if (textField.text.length == 0 || [textField.text isEqualToString:textField.placeholder]) {
        textField.text = textField.placeholder;
        if(textField.tag == 901){
            textField.secureTextEntry = NO;
        }
    }else{
        //手机号框
        if(textField.tag == 902){
            BOOL flag = [self authenticatePhoneNum:textField.text];
            if (!flag) {
                [self showAlert:@"注 意" andAlertString:@"请输入正确的手机号" andHandler:^(UIAlertAction *action) {
                    textField.text = nil;
                }];
            }
        }
    }
    return YES;
}
#pragma mark --- 功能方法
/**
 * 登录成功后跳转页面方法
 */
-(void)presentToMainView{
    LLT_TabBarController_LXM *tabbarController = [MainStoryBoard instantiateViewControllerWithIdentifier:@"tabbarController"];
    LLT_MenuTableViewController_LXH *munuController = [[LLT_MenuTableViewController_LXH alloc]init];
    REFrostedViewController *frostedViewController = [[REFrostedViewController alloc]initWithContentViewController:tabbarController menuViewController:munuController];
    frostedViewController.direction = REFrostedViewControllerDirectionLeft;
    frostedViewController.liveBlurBackgroundStyle = REFrostedViewControllerLiveBackgroundStyleLight;
    frostedViewController.modalTransitionStyle =
    UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:frostedViewController animated:YES completion:nil];
}
/**
 * 设置显示主界面
 */
-(void)makeMainView{
    __weak typeof(self) weakSelf = self;
    AVQuery *query = [AVQuery queryWithClassName:@"LLT_PlayerInfo"];
    NSDictionary *onlineUser =[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"onlineUser"];
    
    [query whereKey:@"phoneNumber" equalTo:onlineUser[@"username"]];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // 检索成功
            if (objects.count > 0) {
                NSDictionary *dic = objects[0];
                weakSelf.player = [LLT_PlayerModel new];
                weakSelf.player.playerName = dic[@"pname"];
                weakSelf.player.serverName = dic[@"pserverName"];
                [weakSelf makeMainViewByBing:YES];
            }else{
                [weakSelf makeMainViewByBing:NO];
            }
        } else {
            [weakSelf makeMainViewByBing:NO];
        }
    }];
}

/**
 * 根据真假判断页面如何调用
 */
-(void)makeMainViewByBing:(BOOL)lock{
    [[NSUserDefaults standardUserDefaults] setBool:lock forKey:@"hasPlayer"];
    LLT_TabBarController_LXM *tabbarController = [self getTabBarWithBrinding:lock];
    LLT_MenuTableViewController_LXH *munuController = [[LLT_MenuTableViewController_LXH alloc]init];
    REFrostedViewController *frostedViewController = [[REFrostedViewController alloc]initWithContentViewController:tabbarController menuViewController:munuController];
    frostedViewController.direction = REFrostedViewControllerDirectionLeft;
    frostedViewController.liveBlurBackgroundStyle = REFrostedViewControllerLiveBackgroundStyleLight;
    frostedViewController.modalTransitionStyle =
    UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:frostedViewController animated:YES completion:nil];
    
}

/**
 * 设置tabBarController
 */
-(LLT_TabBarController_LXM *)getTabBarWithBrinding:(BOOL)brinding{
    
    LLT_TabBarController_LXM *tabbarController = [LLT_TabBarController_LXM shareTabBar];
    LLT_DataViewController_LXM  *dataVC = getVC(@"dataView_Table");
    LLT_PlayerInfoViewController_LXM  *playVC = getVC(@"playerInfoVC");
    LLT_AddPlayerInfoViewController_LXM  *aPlayVC = getVC(@"addPlayerInfoVC");
    LLT_NewsViewController_LXH  *newsVC = getVC(@"newsVC");
    LLT_VideoViewController_LXH  *lVVC = getVC(@"liveAndVideoVC");
    
    //此处添加判定条件(根据是否绑定游戏角色来判断)
    if (brinding && self.player) {
        NSArray *arr = @[playVC,dataVC,newsVC,lVVC];
        playVC.player = self.player;
        [tabbarController setViewControllers:arr];
    }else{
        NSArray *arr = @[aPlayVC,dataVC,newsVC,lVVC];
        [tabbarController setViewControllers:arr];
    }
    return tabbarController;
}

/**
 * 测试代码
 */
-(void)test{
    NSUserDefaults *loginDefault = [NSUserDefaults standardUserDefaults];
    //NSLog(@"userDefault的bool值:%d",[loginDefault boolForKey:@"online"]);
    //NSLog(@"userDefault的user值:%@",[loginDefault dictionaryForKey:@"onlineUser"]);
    //NSLog(@"userDefault的userList值:%@",[loginDefault arrayForKey:@"usersList"]);
}

/**
 * 向nsuserdefault传值
 */
-(void)addUserDefault:(AVUser *)user{
    BOOL flag = YES;
    NSString *password = [self md5StrWithString:self.passwordField.text];
    for (NSDictionary *dic in self.usersList) {
        if (dic[self.userNameField.text]) {
            flag = NO;
        }
    }
    self.avuser = user;
    //更改登录状态为真
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"online"];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"online"];
    //添加需要登录信息
    NSDictionary *dicUser = @{@"username":user.mobilePhoneNumber,@"password":user.password};
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"onlineUser"];
    [[NSUserDefaults standardUserDefaults] setObject:dicUser forKey:@"onlineUser"];
    if (flag) {
        //添加新用户到user数组
        NSDictionary *dic = @{self.userNameField.text:password};
        [self.usersList addObject:dic];
        [[NSUserDefaults standardUserDefaults] setObject:self.usersList forKey:@"usersList"];
        if (self.tableView) {
            [self.tableView removeFromSuperview];
            self.tableView = nil;
            [self makeTableView];
            self.tableView.hidden = YES;
        }
    }
}

/**
 * 创建添加tableView
 */
-(void)makeTableView{
    if (!self.tableView) {
        CGRect frame = self.usernameAndPasswordView.frame;
        NSInteger height = self.usersList.count*30;
        if (height > 100) {
            height = 100;
        }
        CGRect tabelFrame = CGRectMake(frame.origin.x,frame.origin.y+58 ,frame.size.width ,height);
        UITableView *table = [[UITableView alloc]initWithFrame:tabelFrame style:UITableViewStylePlain];
        table.delegate = self;
        table.dataSource = self;
        UIImageView *bg = [[UIImageView alloc]initWithFrame:table.bounds];
        bg.image = [UIImage imageNamed:@"bg_share_large"];
        [table.backgroundView addSubview:bg];
        table.layer.masksToBounds = YES;
        table.layer.cornerRadius = 3;
        table.alpha = 0.8;
        [table registerNib:[UINib nibWithNibName:@"LLT_LoginUserListCell_LXM" bundle:nil]forCellReuseIdentifier:@"userListCell"];
        self.tableView = table;
        [self.bodyView addSubview:self.tableView];
    }
}

#pragma mark --- 点击事件的处理

/**
 * 点击屏幕四周的touch事件
 */
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.userNameField resignFirstResponder];
    [self.passwordField resignFirstResponder];
    self.bodyView.bounds = CGRectMake(0, 0, self.bodyView.frame.size.width, self.bodyView.frame.size.height);
    if (self.tableView) {
        self.tableView.hidden = YES;
    }
}

/**
 * 点击登陆按钮
 */
- (IBAction)didClickLoginButton:(UIButton *)sender {
    //确认所有内容都非空且不等于placeHoder
    BOOL getLengthBool = self.userNameField.text.length == 0 || self.passwordField.text.length == 0 ;
    BOOL getEqualBool = [self.userNameField.text isEqualToString:self.userNameField.placeholder] || [self.passwordField.text isEqualToString:self.passwordField.placeholder];
    if (getLengthBool || getEqualBool) {
        [self showAlert:@"注 意" andAlertString:@"请输入正确的信息"];
    }else{
        NSString *password = [self md5StrWithString:self.passwordField.text];
        [AVUser logInWithMobilePhoneNumberInBackground:self.userNameField.text password:password block:^(AVUser *user, NSError *error) {
            if (error) {
                NSString *message = error.userInfo[@"error"];
                if ([error.userInfo[@"error"] isEqualToString:@"The username and password mismatch."]) {
                    message = @"用户名或密码错误";
                }
                [self showAlert:@"提 示" andAlertString:message];
            }else{
                user.password = password;
                [self addUserDefault:user];
                [self test];
                //最新的登录方法
                [self makeMainView];
            }
        }];
    }
}


/**
 * 点击开始密码保护或者不开启
 */
- (IBAction)didClickShowSecretOrClose:(UIButton *)sender {
    self.passwordField.secureTextEntry = !self.passwordField.secureTextEntry;
}

/**
 * 点击用户名右侧下拉按钮
 */
- (IBAction)didClickDropDownButton:(UIButton *)sender {
    self.tableView.hidden = !self.tableView.hidden;
    [self makeTableView];
}


/**
 * 点击忘记密码
 */
- (IBAction)didClickForgetPasswordButton:(UIButton *)sender {
    
    LLT_RegistViewController_LXM *forgetVC = [MainStoryBoard instantiateViewControllerWithIdentifier:@"registVC"];
    forgetVC.pageTypeFlag = YES;
    forgetVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:forgetVC animated:YES completion:nil];
    
}

/**
 * 点击游客模式
 */
- (IBAction)didClickTouristModeButton:(UIButton *)sender {
    
    [AVAnonymousUtils logInWithBlock:^(AVUser *user, NSError *error) {
    if (user) {
        self.avuser = user;
        [self makeMainViewByBing:NO];
        } else {
            [self showAlert:@"提 示" andAlertString:@"登陆失败"];
            
        }
    }];


}

#pragma mark -- 其他方法

/**
 * 设置电源栏反颜色
 *
 * @return
 */
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
